<script setup>
import { onMounted, onBeforeUnmount, ref, watch } from "vue";
import Chart from "chart.js/auto";

const props = defineProps({
  data: Object,
});

const chartRef = ref(null);
let chartInstance = null;
let resizeObserver = null;

const renderChart = () => {
  if (chartInstance) chartInstance.destroy();

  chartInstance = new Chart(chartRef.value, {
    type: "pie",
    data: props.data,
    options: {
      responsive: true,
      maintainAspectRatio: false,
    },
  });
};

onMounted(() => {
  renderChart();
  resizeObserver = new ResizeObserver(() => {
    if (chartInstance) chartInstance.resize();
  });
  resizeObserver.observe(chartRef.value.parentNode);
});

watch(() => props.data, renderChart, { deep: true });

onBeforeUnmount(() => {
  if (chartInstance) chartInstance.destroy();
  if (resizeObserver) resizeObserver.disconnect();
});
</script>

<template>
  <div style="width: 100%; height: 400px;">
    <canvas ref="chartRef"></canvas>
  </div>
</template>
